﻿<%@ WebHandler Language="C#" Class="AchievementDetail" %>


using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;

public class AchievementDetail : AjaxHandlerBase
{
    public AchievementDetail()
    {
        //导出
        htTypePermit.Add("export", Constants.Permit_AchievementDetail_Export);
    }
    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                case "getlist":
                    GetList(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private void GetList(HttpContext context)
    {
        try
        {
            StringBuilder sb = new StringBuilder();
            //权限
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ArchivementDetailSearch_All))
            {
                sb.Append(" (1=1) ");
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ArchivementDetailSearch_City))
            {
                sb.AppendFormat(" EXISTS(Select 1 from v_Hr_DepartmentInfo M WHERE v_Contract_CommisionDetailInfo.DepartId=M.DepartId And M.cityid='{0}') ", CurrentUserInfo.CityId.ToString());
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ArchivementDetailSearch_Company))
            {
                sb.AppendFormat(" EXISTS(Select 1 from v_Hr_DepartmentInfo M WHERE v_Contract_CommisionDetailInfo.DepartId=M.DepartId And M.companyid='{0}') ", CurrentUserInfo.CompanyId.ToString());
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ArchivementDetailSearch_Depart))
            {
                sb.Append(" EXISTS(");
                sb.Append(string.Format("Select 1 from t_Business_EmpSetting M WHERE v_Contract_CommisionDetailInfo.DepartId=M.DepartId And M.Userid= '{0}' and SearchAchievementDetail=1", CurrentUserInfo.UserId.ToString()));
                sb.Append(") ");
            }
            else
            {
                sb.AppendFormat(" (EmployeeId = '{0}') ",CurrentUserInfo.UserId);
            }

            //查询4级
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid userId = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);
            
            if (userId != Guid.Empty)
                sb.AppendFormat(" AND (EmployeeId = '{0}') ", userId);
            else if (departs != Guid.Empty)
            {
                sb.AppendFormat(" and departid = '{0}'", departs);
            }
            else if (businessdistrict != Guid.Empty)
            {
                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
                string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
                if (!cs.Hit)
                {
                    item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                    if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
                }

                if (item == null)
                {
                    context.Response.Write(retExecResult(Constants.ExecResult.Error, "获取商圈或分类数据丢失", ""));
                }
                sb.AppendFormat(" and (departid in (Select DepartId from v_Hr_DepartmentInfo where DepartSrc like '{0}%'))", item.DepartSrc);
            }
            else if (company != Guid.Empty)
            {
                sb.AppendFormat(" and (departid in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", company);
            }
            else if (city != Guid.Empty)
            {
                sb.AppendFormat(" and (departid in (Select DepartId from v_Hr_DepartmentInfo WHERE cityid='{0}')) ", city);
            }
            else
            {
                sb.AppendFormat(" and (departid in (select DepartId from v_Hr_DepartmentInfo WHERE companyid='{0}')) ", CurrentUserInfo.CompanyId);
            }

            
            //查询条件
            if ("10".Equals(context.Request["type"]))
            {
                if (!string.IsNullOrEmpty(context.Request["starttime"]))
                {
                    sb.AppendFormat(" and ArchivementDate >= '{0}'", context.Request["starttime"]);
                }
                if (!string.IsNullOrEmpty(context.Request["endtime"]))
                {
                    sb.AppendFormat(" and ArchivementDate <= '{0}'", context.Request["endtime"]);
                }
            }
            else if ("20".Equals(context.Request["type"])) {
                if (!string.IsNullOrEmpty(context.Request["starttime"]))
                {
                    sb.AppendFormat(" and ContractDate >= '{0}'", context.Request["starttime"]);
                }
                if (!string.IsNullOrEmpty(context.Request["endtime"]))
                {
                    sb.AppendFormat(" and ContractDate <= '{0}'", context.Request["endtime"]);
                }
            }
            //查询条件10=买卖(主营)；20=租赁(主营)；30=零散业务；40=其他业务
            if (!string.IsNullOrEmpty(context.Request["status"]) && !"50".Equals(context.Request["status"]))
            {
                sb.AppendFormat(" and BusinessType = '{0}' ", context.Request["status"]);
            }
            if (!string.IsNullOrEmpty(context.Request["keyWord"]))
            {
                sb.AppendFormat(" and (ContractCode Like '%{0}%' OR HouseAddress Like '%{0}%' OR Community Like '%{0}%') ", context.Request["keyWord"]);
            }

            //描述：快速搜索参数拼接
            if (context.Request["quicktype"] != null)
            {
                switch (context.Request["quicktype"])
                {
                    case "owner"://我的房源
                        sb.AppendFormat(" And (EmployeeId='{0}')", CurrentUserInfo.UserId);
                        break;
                    case "depart"://本店房源
                        sb.AppendFormat(" And (DepartId='{0}')", CurrentUserInfo.DepartId);
                        break;
                }
            }
            
            sb.Append(" and bArchivement=1 ");

            int iPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
            int iPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 100 : int.Parse(context.Request["pagesize"]);//页记录数
            //order文
            string strOrder = "v_Contract_CommisionDetailInfo.DepartId desc";
            if (!string.IsNullOrEmpty(context.Request["sort"]))
                strOrder = context.Request["sort"];
            
            //查询表格
            string tablename = "v_Contract_CommisionDetailInfo";
            //select文
            string TableFieldList = "dbo.FN_GetBussinessByDepartID(departid) as business,ContractCode,ContractDate,Depart,Region,HouseAddress,Employee,DeparterManagerName,MangerName,RegionManagerName,MajordomoName,AllCommision,AllBeforeCommision,AllConsulting,PureCommision,Point,ApportionAR,ApportionConsulting,ApportionCommision,ArchivementDate,BargainCompanyName";
            string FieldList = "business,ContractCode,ContractDate,Depart,Region,HouseAddress,Employee,DeparterManagerName,RegionManagerName,MajordomoName,MangerName,AllCommision,AllBeforeCommision,AllConsulting,PureCommision,Point,ApportionAR,ApportionConsulting,ApportionCommision,ArchivementDate,BargainCompanyName";

            //string strSql = "select " + TableFieldList + " from " + tablename + " where " + sb.ToString() + " order by " + strOrder;
            
            //根据sql执行查询
            DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(iPageIndex, iPageSize, strOrder, tablename, sb.ToString(), FieldList, TableFieldList, true);

            context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[1].Rows[0][0], Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
            //DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

            //string html = GetHtml(ds.Tables[0]);

            //context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
            //context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},html:'{1}'}}}}", ds.Tables[0].Rows.Count, html));
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private string GetHtml(DataTable dt)
    {
        StringBuilder sb = new StringBuilder();
        decimal yj = 0; //业绩
        decimal point = 0;  //点数
        decimal ss = 0; //分摊实收
        decimal zxf = 0;    //分摊咨询费
        decimal ftyj = 0;   //分摊业绩

        foreach (DataRow dr in dt.Rows)
        {
            //sb.Append("<dl>");
            //sb.AppendFormat("<dd>{0}</dd>", dr["business"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["Depart"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["ContractCode"]);
            //sb.AppendFormat("<dd>{0:yyyy-MM-dd}</dd>", dr["ContractDate"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["Region"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["HouseAddress"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["Employee"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["DeparterManagerName"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["RegionManagerName"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["MajordomoName"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["AllCommision"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["AllBeforeCommision"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["AllConsulting"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["PureCommision"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["Point"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["ApportionAR"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["ApportionConsulting"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["ApportionCommision"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["ArchivementDate"]);
            //sb.AppendFormat("<dd>{0}</dd>", dr["BargainCompanyName"]);
            //sb.Append("</dl>");

            sb.Append("<tr>");
            sb.AppendFormat("<td>{0}</td>", dr["business"]);
            sb.AppendFormat("<td>{0}</td>", dr["Depart"]);
            sb.AppendFormat("<td>{0}</td>", dr["ContractCode"]);
            sb.AppendFormat("<td>{0:yyyy-MM-td}</td>", dr["ContractDate"]);
            sb.AppendFormat("<td>{0}</td>", dr["Region"]);
            sb.AppendFormat("<td>{0}</td>", dr["HouseAddress"]);
            sb.AppendFormat("<td>{0}</td>", dr["Employee"]);
            sb.AppendFormat("<td>{0}</td>", dr["DeparterManagerName"]);
            sb.AppendFormat("<td>{0}</td>", dr["RegionManagerName"]);
            sb.AppendFormat("<td>{0}</td>", dr["MajordomoName"]);
            sb.AppendFormat("<td>{0}</td>", dr["AllCommision"]);
            sb.AppendFormat("<td>{0}</td>", dr["AllBeforeCommision"]);
            sb.AppendFormat("<td>{0}</td>", dr["AllConsulting"]);
            sb.AppendFormat("<td>{0}</td>", dr["PureCommision"]);
            sb.AppendFormat("<td>{0}</td>", dr["Point"]);
            sb.AppendFormat("<td>{0}</td>", dr["ApportionAR"]);
            sb.AppendFormat("<td>{0}</td>", dr["ApportionConsulting"]);
            sb.AppendFormat("<td>{0}</td>", dr["ApportionCommision"]);
            sb.AppendFormat("<td>{0}</td>", dr["ArchivementDate"]);
            sb.AppendFormat("<td>{0}</td>", dr["BargainCompanyName"]);
            sb.Append("</tr>");

            yj += (decimal)dr["PureCommision"];
            point += (decimal)dr["Point"];
            ss += (decimal)dr["ApportionAR"];
            zxf += (decimal)dr["ApportionConsulting"];
            ftyj += (decimal)dr["ApportionCommision"];
        }
        sb.Append("<tr><td>总计</td>");
        sb.Append("<td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>");
        sb.AppendFormat("<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td></td><td></td></tr>",yj,point,ss,zxf,ftyj);
        
        return sb.ToString();
    }
}